/**
 * 3D Scene Component with React Three Fiber
 * Requirements: 1.1, 1.3
 */

import { Canvas, useThree } from '@react-three/fiber';
import { Scene3DProps } from '@/types';
import { MobiusBackground } from './MobiusBackground';
import { FloatingObjectRenderer } from './FloatingObjects';
import { Suspense, useEffect, useRef } from 'react';

/**
 * Parallax camera controller component
 * Requirements: 1.3 - Implements parallax effect on mouse movement
 */
function ParallaxCamera({ enabled }: { enabled: boolean }) {
  const { camera } = useThree();
  const mousePosition = useRef({ x: 0, y: 0 });

  useEffect(() => {
    if (!enabled) return;

    const handleMouseMove = (event: MouseEvent) => {
      // Normalize mouse position to -1 to 1 range
      mousePosition.current.x = (event.clientX / window.innerWidth) * 2 - 1;
      mousePosition.current.y = -(event.clientY / window.innerHeight) * 2 + 1;

      // Apply subtle parallax effect to camera position
      const parallaxStrength = 0.5;
      camera.position.x = mousePosition.current.x * parallaxStrength;
      camera.position.y = mousePosition.current.y * parallaxStrength;
      
      // Make camera look at the center
      camera.lookAt(0, 0, 0);
    };

    window.addEventListener('mousemove', handleMouseMove);

    return () => {
      window.removeEventListener('mousemove', handleMouseMove);
    };
  }, [enabled, camera]);

  return null;
}

/**
 * Main 3D Scene component that renders the Canvas with camera, lighting, and background
 */
export function Scene3D({ objects, enableParallax, onLoad }: Scene3DProps) {
  // Debug: Log objects count
  console.log('Scene3D rendering with', objects.length, 'objects');
  
  return (
    <div className="fixed inset-0 z-0" style={{ pointerEvents: 'none' }}>
      <Canvas
        camera={{
          position: [0, 0, 10],
          fov: 75,
          near: 0.1,
          far: 1000
        }}
        onCreated={() => {
          console.log('Canvas created successfully');
          onLoad?.();
        }}
      >
        {/* Parallax camera controller */}
        <ParallaxCamera enabled={enableParallax} />
        
        {/* Ambient light for overall scene illumination */}
        <ambientLight intensity={0.5} />
        
        {/* Directional light for depth and shadows */}
        <directionalLight position={[10, 10, 5]} intensity={1} />
        
        {/* Point lights for dynamic lighting */}
        <pointLight position={[-10, -10, -5]} intensity={0.5} color="#ff00ff" />
        <pointLight position={[10, -10, -5]} intensity={0.5} color="#00ffff" />
        
        {/* Mobius-style background */}
        <Suspense fallback={null}>
          <MobiusBackground />
        </Suspense>
        
        {/* Floating objects will be rendered here */}
        {objects.map((obj) => (
          <FloatingObjectRenderer key={obj.id} object={obj} />
        ))}
      </Canvas>
    </div>
  );
}
